package broth.gdt;

import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class CenterLocationOverlay extends Overlay {
	
	Resources res;
	MapTrackActivity mother;
	boolean visible = true;
	Drawable icon;
	Rect rect;
	int x = 7;
	int y = 11;
	Projection projection;
	Point point;
	
	// get the icon resources and map activity context
	public CenterLocationOverlay(Resources resources, MapTrackActivity context) {
		res = resources;
		mother = context;
	}
	
	// draw the overlay
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		
		// if the overlay is visible
		if(visible == true) {
			
			// get the drawable, set the location and size, and draw to canvas
			icon = res.getDrawable(android.R.drawable.ic_menu_mylocation);
			rect = new Rect(x, y, x+icon.getIntrinsicWidth(), y+icon.getIntrinsicHeight());
			icon.setBounds(rect);
			icon.draw(canvas);
		}
	}
	
	// called when the map is tapped
	@Override
	public boolean onTap(GeoPoint p, MapView mapView) {
		super.onTap(p, mapView);
		
		// if the overlay is visible
		if(visible == true) {
			
			// map the current view to pixel number
			projection = mapView.getProjection();
			point = projection.toPixels(p, null);
			
			// check if tap was on center location overlay
			if( (point.x > x) && (point.y > y) &&
					(point.x < x+icon.getIntrinsicWidth()) &&
					(point.y < y+icon.getIntrinsicHeight()) ) {
				
				// center the view to user location
				mother.center_user_location();
				
				// hide the overlay
				visible = false;
				
				return true;
			}
			else {
				return false;
			}
		}
		else {
			return false;
		}
	}
	
	// called when the user touches the screen
	@Override
	public boolean onTouchEvent(MotionEvent e, MapView mapView) {
		
		// push the event upwards (to handle other actions)
		super.onTouchEvent(e,  mapView);
		
		// if the touch was a swipe (move)
		if(((e.getAction()) & (MotionEvent.ACTION_MOVE)) != 0) {
			
			// stop holding the users location
			mother.drop_user_location();
			
			// and make the overlay visible
			visible = true;
		}
		return false;
	}

}
 